layui.use(['element', 'form', 'table', 'laytpl'], function () {
    var $ = layui.$,
        table = layui.table,
        layer = layui.layer,
        form = layui.form;
    var tableIns = table.render({
        elem: '#demo'
        , id: "mytable"
        , url: '/room/list' //数据接口
        , page: true //开启分页
        , limit: 15
        , limits: [15, 30, 60, 100]
        , response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            , statusCode: 200 //成功的状态码，默认：0
            , msgName: 'msg' //状态信息的字段名称，默认：msg
            , countName: 'total' //数据总数的字段名称，默认：count
            , dataName: 'rows' //数据列表的字段名称，默认：data
        }
        , cols: [[ //表头
            {type: 'checkbox'}
            , {title: '序号', type: 'numbers'}
            // , {field: 'tag', title: '房间标签'}
            , {
                title: '编号', templet: function (d) {
                    return d.buildingName + '-' + d.code;
                }
            }
            // , {field: 'buildingName', title: '所属楼宇'}
            //             // , {field: 'floor', title: '所属楼层'}
            , {
                field: 'bedNum', title: '床位数', templet: function (d) {
                    if (d.bedNum > 0) {
                        return "<font color='#dc143c'>" + d.bedNum + "</font>";
                    }
                    return d.bedNum;
                }
            }
            // , {
            //     field: 'area', title: '房间面积', templet: function (d) {
            //         return d.area + " m<sup>2</sup>"
            //     }
            // }
            , {
                field: 'status', title: '房间状态', templet: function (d) {
                    switch (d.status) {
                        case 1:
                            return '可用';
                        case 2:
                            return '满员';
                        case 3:
                            return '停用';
                        default:
                            return '';
                    }
                }
            }
            , {
                field: 'direction', title: '房间朝向', templet: function (d) {
                    switch (d.direction) {
                        case 1:
                            return '朝南';
                        case 2:
                            return '朝北';
                        case 3:
                            return '超西';
                        case 4:
                            return '朝东';
                        default:
                            return '';
                    }
                }
            }
            , {title: '操作', toolbar: "#toolbar", width: "18%"}

        ]]
    });

    form.on('select(buildingNo)', function (data) {
        var buildingId = $(data.elem).find("option:selected").attr("id");
        if (data.value) {
            $.ajax({
                url: "/room/floors",
                data: {buildingId: buildingId},
                dataType: 'json',
                success: function (rs) {
                    $("#floorNo").empty().append('<option value="">请选择楼层</option>');
                    if (rs.code == 200) {
                        $.each(rs.data, function (i, r) {
                            $("#floorNo").append('<option value="' + r + '">' + r + '</option>');
                        });
                    }
                    form.render('select'); //刷新select选择框渲染
                }
            });
        }
    });
    //工具条
    table.on("tool(test)", function (obj) {
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        if ("edit" == layEvent) {
            location.href = "/room/edit?id=" + data.id;
        } else if ("delete" == layEvent) {
            var params = "roomId=" + data.id;
            layer.open({
                title: '提示',
                type: 1,
                content: "删除该房间则会删除对应的床位，您确认删除该房间吗？",
                area: ['400px', '150px'],
                btn: ['确认'],
                yes: function (index, layero) {
                    $.ajax({
                        type: 'post',
                        url: '/bed/selecBedtList',
                        dataType: 'json',
                        data: params,
                        success: function (result) {
                            if (result.code == 0) {
                                layer.msg("该房住有老人，不能删除。");
                            } else {
                                location.href = "/room/delete?id=" + data.id;
                            }
                        }
                    });
                }
            });

        } else if ("bed" == layEvent) {
            var broomNum = data.code;//房间号
            var buildingId = data.buildingId;//楼宇id
            var roomId = data.id;//房间id
            var usertype = $("#usertype").val();
            if (usertype == 2) {//民办机构
                var troption = "";
                $.ajax({
                    type: 'post',
                    url: '/bedtype/selectBedTypeList',
                    dataType: 'json',
                    async: false,
                    success: function (result) {
                        $.each(result.data, function (i, d) {
                            troption += ' <option value="' + d.id + '">' + d.name + '</option>\n';
                        })
                    }
                });
                addtr =
                    '                       <tr>\n' +
                    '                            <td><input type="text" readonly autocomplete="off" class="layui-input" value="' + data.buildingName + '"></td>\n' +
                    '                            <td><input type="text" readonly autocomplete="off" class="layui-input" value="' + data.floor + '"></td>\n' +
                    '                            <td><input type="text" readonly autocomplete="off" class="layui-input" value="' + broomNum + '"></td>\n' +
                    '                            <td> <input type="number" name="code" id="code" readonly placeholder="床位号" autocomplete="off" class="layui-input" value="1"></td>\n' +
                    '                            <td>   <select name="typeId" lay-verify="required" \n' +
                    '                                                <option value=""></option>\n' +
                    troption +
                    '                                           </select></td>\n' +
                    '                           <td><button  type="button"  onclick="delRow(this)" class="layui-btn layui-btn-danger layui-btn-xs" >删除</button></td>\n' +
                    '                       </tr>';
            } else {
                addtr =
                    '                       <tr>\n' +
                    '                            <td><input type="text"  readonly autocomplete="off" class="layui-input" value="' + data.buildingName + '"></td>\n' +
                    '                            <td><input type="text" readonly autocomplete="off" class="layui-input" value="' + data.floor + '"></td>\n' +
                    '                            <td><input type="text"  readonly autocomplete="off" class="layui-input" value="' + broomNum + '"></td>\n' +
                    '                            <td> <input type="number" name="code" id="code" readonly placeholder="床位号" autocomplete="off" class="layui-input" value="1"></td>\n' +
                    '                            <td>   <select name="type" lay-verify="required" \n' +
                    '                                                <option value=""></option>\n' +
                    '                                               <option value="1">普通床位</option>\n' +
                    '                                                <option value="2">护理床位</option>\n' +
                    '                                           </select></td>\n' +
                    '                           <td><button  type="button"  onclick="delRow(this)" class="layui-btn layui-btn-danger layui-btn-xs" >删除</button></td>\n' +
                    '                       </tr>';
            }
            var html =
                '<form class="layui-form" id="openForm">' +
                '  <table class="layui-table">\n' +
                '                        <colgroup>\n' +
                '                            <col width="150">\n' +
                '                            <col width="100">\n' +
                '                            <col width="100">\n' +
                '                            <col width="150">\n' +
                '                            <col width="200">\n' +
                '                            <col width="100">\n' +
                '                        </colgroup>\n' +
                '                        <thead>\n' +
                '                        <tr>\n' +
                '                            <th>楼宇</th>\n' +
                '                            <th>楼层</th>\n' +
                '                            <th>房间号</th>\n' +
                '                            <th>床位号</th>\n' +
                '                            <th>床位类型</th>\n' +
                '                            <th>操作</th>\n' +
                '                        </tr>\n' +
                '                        </thead>\n' +
                '                        <tbody id="tbody">\n' +
                addtr +
                '                       </tbody>\n' +
                '                    </table>' +
                '                   <div class="layui-btn-group" style="margin-left: 20px;">\n' +
                '                       <button class="layui-btn layui-btn-sm"   type="button" onclick="addRow()" >\n' +
                '                           <i class="layui-icon">&#xe654;</i>\n' +
                '                       </button>\n' +
                '                   </div>\n' +
                '</form>';
            $.ajax({
                type: 'post',
                url: '/bed/selecBedts',
                dataType: 'json',
                data: {roomId: roomId},
                success: function (result) {
                    if (result.data.length > 0) {
                        layer.open({
                            title: '提示',
                            type: 1,
                            content: "<div>该房间已快速生成过床位，不能再次生成，如需添加床位请前往床位管理点击新增按钮<a href='/bed/add' style='color: blue'>>>>>>前往床位新增</a></div>",
                            area: ['400px', '150px']
                        });
                        return false;
                    } else {
                        n = 2;
                        layer.open({
                            title: '床位管理'
                            , area: ['740px', '500px']
                            , btn: ['生成', '取消']
                            , content: html
                            , type: 1
                            , success: function (layero, index) {
                                form.render(); //更新全部
                            }
                            , yes: function (index, layero) {
                                //按钮【生成】的回调
                                var usertype = $("#usertype").val();
                                var flag=false;
                                if (usertype == 2) {
                                    $("#tbody td select").each(function () {
                                        if ($(this).val()==null || $(this).val()==undefined || $(this).val()=="" ){
                                           flag =true;
                                           //停止循环
                                            return false;
                                        }
                                    })
                                }
                                if (flag){
                                    layer.close(index);
                                    parent.layer.msg("床位类型不能为空");
                                    return;
                                }
                                //修改房间床位数
                                var bedNum = $("#tbody").find("tr").size();
                                if (bedNum==0){
                                    layer.close(index);
                                    parent.layer.msg("无效操作");
                                    return;
                                }
                                if (bedNum > 0) {
                                    $.ajax({
                                        type: 'post',
                                        url: '/room/update',
                                        dataType: 'json',
                                        data: {"id": roomId, "bedNum": bedNum, "floor": data.floor, "status": 1},
                                        success: function (result) {
                                        }
                                    });
                                }
                                var params = $("#openForm").serialize();
                                params += "&buildingId=" + buildingId + "&roomId=" + roomId + "&floor=" + data.floor;
                                $.ajax({
                                    type: 'post',
                                    url: '/bed/saveList',
                                    dataType: 'json',
                                    data: params,
                                    success: function (result) {
                                        //正确处理
                                        if (result.code == 200) {
                                            layer.msg("创建床位成功", {
                                                time: 1000
                                            }, function () {
                                                layer.close(index);
                                                var params = $("#search-form").serializeObject();
                                                tableIns.reload({
                                                    where: params //设定异步数据接口的额外参数
                                                });
                                            });
                                        }
                                    }
                                });
                                layer.close(index);
                            }
                        });
                    }
                }
            })
        }
    });

    /**
     * 搜索
     */
    $("#search").on('click', function () {
        var params = $("#search-form").serializeObject();
        tableIns.reload({
            where: params //设定异步数据接口的额外参数
        });
    });

    delRow = function (that) {
        $(that).closest("tr").remove();
    }
    var n = 2;
    addRow = function () {
        $("#tbody").append(addtr);
        form.render(); //更新全部
        $("#tbody").find("tr:last").find("#code").val(n);
        n++;
    }
});